package com.gxan.web.controller;

import com.alibaba.fastjson.JSONObject;
import com.gxan.common.R;
import com.gxan.service.UserService;
import com.gxan.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/*
登录功能
 */
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.验证验证码是否正确
        //输入框输入的验证码值
        String vercode = request.getParameter("vercode");
        //获取session域中获取生成验证码
        String serverVerCode = request.getSession().getAttribute("serverVerCode").toString();
        //创建R对象
        R r = new R();
        if(!serverVerCode.equalsIgnoreCase(vercode)){
            //不正确
            r.setCode(401);
            r.setMsg("验证码错误");
        }else{
            //正确
            //2.用户名和密码是否正确
            //获取输入框用户名和密码值
            String username = request.getParameter("username");
            Integer password = Integer.parseInt(request.getParameter("password"));
            //调用service
            UserService userService = new UserServiceImpl();
            r = userService.login(username, password);
        }

        //转成JSON响应回login.html
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(JSONObject.toJSONString(r));
        System.out.println(r.getData());
        response.getWriter().flush();
        response.getWriter().close();
    }
}
